package com.timmy.google_play.fragment;

import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ListView;

import com.timmy.google_play.base.BaseFragment;
import com.timmy.google_play.base.BaseHolder;
import com.timmy.google_play.base.ListViewFactory;
import com.timmy.google_play.base.LoadingPager;
import com.timmy.google_play.base.SuperBaseAdapter;
import com.timmy.google_play.bean.CategoryBean;
import com.timmy.google_play.holder.category.CategoryNormalHolder;
import com.timmy.google_play.holder.category.CategoryTitleHolder;
import com.timmy.google_play.protocol.CategoryProtocol;

import java.util.List;

/**
 * Created by Timmy on 2016/12/7.
 */
public class CategoryFragment extends BaseFragment {

    private List<CategoryBean> mDatas;

    @Override
    protected LoadingPager.LoadedResult initData() {

        CategoryProtocol protocol = new CategoryProtocol();

        try {
            mDatas = protocol.loadData(0);

            return checkResData(mDatas);

        } catch (Exception e) {
            e.printStackTrace();
            return LoadingPager.LoadedResult.ERROR;
        }
    }

    @Override
    protected View initSuccessView() {

        ListView listView = ListViewFactory.createListView();

        listView.setAdapter(new CategoryAdapter(listView, mDatas));

        return listView;
    }

    static class CategoryAdapter extends SuperBaseAdapter<CategoryBean> {

        public CategoryAdapter(ListView listView, List<CategoryBean> datas) {
            super(listView, datas);
        }

        @NonNull
        @Override
        protected BaseHolder<CategoryBean> getSpecialBaseHolder(int position) {

            CategoryBean categoryBean = mDatas.get(position);

            if (categoryBean.isTitle) {
                return new CategoryTitleHolder();
            } else {
                return new CategoryNormalHolder();
            }
        }

        @Override
        public int getViewTypeCount() {
            return super.getViewTypeCount() + 1;
        }

        /*
        @Override
        public int getItemViewType(int position) {
            CategoryBean categoryBean = null;

            if (position != getCount() - 1) {
                categoryBean = mDatas.get(position);
            }

            if (position == getCount() - 1) {
                return 0;
            } else if (categoryBean.isTitle) {
                return 1;
            } else {
                return 2;
            }
        }
        */
        //这两种方法都可以

        @Override
        public int getNormalItemViewType(int position) {
            CategoryBean categoryBean = mDatas.get(position);

            if (categoryBean.isTitle) {
                return 1;
            } else {
                return 2;
            }
        }
    }
}
